package com.itheima.contorller;

import com.itheima.domain.Admin;
import com.itheima.domain.User;
import com.itheima.service.Impl.UserServiceImpl;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
*   用于提供服务方法
* */
@WebServlet("/user/*")
public class UserServlet extends BasicSevlet{

    //创建服务层对象
    UserService service =new UserServiceImpl();

    //登录方法
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端页面获取账号和密码
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        //从服务层获取到查询后的封装对象
        Admin admin = service.findByEmailAndPwd(email, password);
        req.getSession().setAttribute("username", admin.getUsername());
        //判断用户是否为空决定跳转
        if(admin != null){
            req.getRequestDispatcher("/WEB-INF/pages/main.jsp").forward(req,resp);
        }else {
            req.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(req,resp);
        }
    }

    //list方法 获取所有用户
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户列表
        List<User> userList = service.findAll();
        //将userList存放到会话域
        req.getSession().setAttribute("userList",userList);
        //转发到list页面
        req.getRequestDispatcher("/WEB-INF/pages/list.jsp").forward(req,resp);
    }
}
